import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:series_play/comm/base/base_state.dart';
import 'package:series_play/utils/log.dart';
import 'package:series_play/widget/video/app_video_view.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'for_you_controller.dart';

class ForYouVideoFeedPage extends StatefulWidget {
  const ForYouVideoFeedPage({super.key});

  @override
  State<ForYouVideoFeedPage> createState() => _ForYouVideoFeedPageState();
}

class _ForYouVideoFeedPageState
    extends BaseControllerState<ForYouVideoFeedPage, ForYouController> {
  final PageController _pageController = PageController();

  var isBackground = false;

  @override
  Widget buildPage(BuildContext context) {
    final child = Obx(() {
      return PageView.builder(
        scrollDirection: Axis.vertical,
        itemCount: mController.dataList.length,
        onPageChanged: (i) {
          mController.onPageChanged(i);
        },
        itemBuilder: (context, i) {
          return AppVideoView(
            pageController: _pageController,
            index: i,
            baseFeedVideoController: mController,
          );
        },
      );
    });

    return VisibilityDetector(
      key: Key('feed_list_'),
      onVisibilityChanged: (VisibilityInfo info) {
        // 可见比例（0.0 = 完全不可见，1.0 = 完全可见）
        final visibility = info.visibleFraction;
        mController.isPageFullyVisible.value = visibility == 1.0;
        if (visibility == 1.0) {
          Log.wtf("页面完全可见");
        } else if (visibility == 0.0) {
          Log.wtf("页面完全不可见");
        } else {
          Log.wtf("页面部分可见：$visibility");
        }
      },
      child: child,
    );
  }

  @override
  ForYouController createController() {
    return ForYouController();
  }

  @override
  bool hideAppbar() {
    return true;
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 判断当前页面是否可见
    final isVisible = ModalRoute.of(context)?.isCurrent ?? false;
    if (isVisible) {
      Log.wtf("ForYou 可见");
      // 执行可见时的操作（如恢复播放、刷新数据）
    } else {
      Log.wtf("ForYou 不可见");
      // 执行不可见时的操作（如暂停播放、保存状态）
    }
  }
}
